using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using Deepcode.Flux.Core.Systems.Workflow;
using Deepcode.Flux.Core.Systems.Workflow.Bases;
using Deepcode.Flux.Core.Services.Security;

namespace Deepcode.Flux.Core.UI.Controls
{
	/// <summary>
	/// The workflow header control provides automatic information
	/// and actioning of workflow tasks. This is generally used in the
	/// view/edit handlers of a workflow handler to list the available
	/// exit paths for a task. It implements the same logic as the workflow
	/// task list control, but for one task only.
	/// </summary>
	public class WorkflowHeaderControl : System.Web.UI.WebControls.WebControl, INamingContainer
	{
		#region Control Properties
		/// <summary>
		/// Get / Set the task ID this control will work upon
		/// </summary>
		public int TaskID
		{
			get
			{
				object o = ViewState["TaskID"];
				return (o == null) ? -1 : (int)o;
			}
			set
			{
				ViewState["TaskID"] = value;
			}
		}
		#endregion
		protected override void CreateChildControls()
		{
			ShadePadBox sectionhost = new ShadePadBox();
			this.Controls.Add( sectionhost );

			// Load the task
			Task t = new Tasks().GetTasksByID( TaskID );
			if( t == null ) return;

			// Create an engine for the task's handler
			WorkflowEngine Engine = new WorkflowEngine( t.HandlerCodeID );

			// Now, add information about the task
			Literal l = new Literal();
			l.Text = " <font color=black><b>Due:</b></font> " + t.CalcDue;
			l.Text += " <font color=black><b>Task:</b></font> " + t.TaskCaption;
			l.Text += " <hr/>";
			sectionhost.Controls.Add( l );
			// Now build information about the exit paths **********
			HyperLink hb = new HyperLink();
			hb.CssClass = "SafeLink";
			hb.Text = "[Back to Task List]";
			hb.NavigateUrl = "~/admin/Menu/taskpad.aspx";
			sectionhost.Controls.Add(hb);
			
			// Get the Exit Paths available
			foreach (TaskExitPath Path in t.ExitPaths)
			{
				if( AdministrationSecurity.IsMemberOfOneGroupID( Path.CSV_AllowedGroups ))
				{
					// Create a link button with the taskID and exitPathID - unless it's a UI
					if (Path.uiTaskMethod != "")
					{
						HyperLink h = new HyperLink();
						h.CssClass = "SafeLink";
						h.Text = "[" + Path.Caption + "]";
						h.NavigateUrl = Engine.GetExitUI(Path.uiTaskMethod, t.PK_ID, Path.PK_ID);
						sectionhost.Controls.Add(h);
					}
					else
					{
						LinkButton lb = new LinkButton();
						lb.Text = "[" + Path.Caption + "]";
						lb.CssClass = "SafeLink";
						lb.CommandName = "ProcessExitPath";
						lb.CommandArgument = String.Format("{0},{1}", t.PK_ID, Path.PK_ID);
						lb.Click += new EventHandler(CommandHandler);
						sectionhost.Controls.Add(lb);
					}
				}
			}
		}

		private void CommandHandler(object sender, EventArgs e)
		{
			if (!(sender is LinkButton)) return;
			if (((LinkButton)sender).CommandName != "ProcessExitPath") return;
			LinkButton LBSender = (LinkButton)sender;

			string Arguments = (string)LBSender.CommandArgument;
			// Ensure it contains data
			if (Arguments == "") return;
			// Split it into Task/ExitPath ID's
			string[] Args = Arguments.Split(',');
			// Ensure there are two and only two
			if (Args.Length != 2) return;
			// Convert to ID's
			int TaskID = -1;
			int ExitPathID = -1;
			try
			{
				TaskID = Int32.Parse(Args[0]);
				ExitPathID = Int32.Parse(Args[1]);
			}
			catch { return; }
			// Load the task and exit path
			Task t = new Tasks().GetTasksByID( TaskID );
			TaskExitPath ep = new TaskExitPaths().GetTaskExitPathByID( ExitPathID );
			// Ensure it's all valid
			if ((t == null) || (ep == null)) return;
			// Process it
			WorkflowEngine we = new WorkflowEngine( t.HandlerCodeID );
			if( we == null ) return;
			we.ProcessExitAction( TaskID, ExitPathID );
			// Go back to Task List
			Page.Response.Redirect("~/admin/menu/taskpad.aspx", true);
		}
	}
}
